package br.com.rhinovet.autenticacao;

import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;

import javax.faces.context.FacesContext;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.EntityTransaction;
import javax.persistence.Persistence;
import javax.servlet.http.HttpSession;

import org.springframework.stereotype.Service;

import br.com.rhinoadmin.webservice.contract.Usuario;

@Service("conexao")
public class Conexao implements Serializable {
	
	private static final long serialVersionUID = 1L;

	private Map<String, EntityManager> mapConexao = new HashMap<String, EntityManager>();
	
	public EntityManager getEntityManager() {
		
		EntityManager entityManager = null;
		if (mapConexao.get(getUsuarioLogado()) == null) {
			EntityManagerFactory factory = Persistence.createEntityManagerFactory(getUsuarioLogado().toLowerCase()); 
			entityManager = factory.createEntityManager();
			mapConexao.put(getUsuarioLogado(), entityManager);
		} else {
			entityManager = mapConexao.get(getUsuarioLogado());
		}
		return entityManager;
	}

	public EntityTransaction obterTransacao() {
		EntityTransaction transaction = this.getEntityManager().getTransaction();
		return transaction;
	}
	
	public String getUsuarioLogado() {
		HttpSession session = (HttpSession) FacesContext.getCurrentInstance().getExternalContext().getSession(true);
		Usuario usuarioLogado = (Usuario) session.getAttribute("usuarioLogado");
		return usuarioLogado.getEmailInicial();
	}
}
